package com.one.rope.mvp.web.service.company;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.rope.mvp.basecore.bean.AdminBusinessMessage;
import com.one.rope.mvp.basecore.bean.BusinessMessage;
import com.one.rope.mvp.basecore.bean.ResponseMessage;
import com.one.rope.mvp.basecore.exception.BusinessDataException;
import com.one.rope.mvp.basecore.util.JsonUtils;
import com.one.rope.mvp.basecore.util.MyBeanUtils;
import com.one.rope.mvp.basecore.util.StringUtils;
import com.one.rope.mvp.web.business.entity.Company;
import com.one.rope.mvp.web.business.entity.CompanyMember;
import com.one.rope.mvp.web.business.entity.CompanyPartnerIncentive;
import com.one.rope.mvp.web.business.entity.CompanyProject;
import com.one.rope.mvp.web.business.entity.CompanyProjectPartner;
import com.one.rope.mvp.web.business.entity.MemberPushTaskLog;
import com.one.rope.mvp.web.business.entity.SystemConfig;
import com.one.rope.mvp.web.business.service.ICompanyMemberService;
import com.one.rope.mvp.web.business.service.ICompanyPartnerIncentiveService;
import com.one.rope.mvp.web.business.service.ICompanyProjectPartnerService;
import com.one.rope.mvp.web.business.service.ICompanyProjectService;
import com.one.rope.mvp.web.business.service.ICompanyService;
import com.one.rope.mvp.web.business.service.IMemberInfoService;
import com.one.rope.mvp.web.business.service.IMemberPushTaskLogService;
import com.one.rope.mvp.web.business.service.ISystemConfigService;
import com.one.rope.mvp.web.common.auth.UserInfo;
import com.one.rope.mvp.web.common.auth.UserLoginUtil;
import com.one.rope.mvp.web.common.dto.admin.company.EditCompanyDTO;
import com.one.rope.mvp.web.common.dto.admin.partner.CompanyPartnerDetailVO;
import com.one.rope.mvp.web.common.dto.admin.partner.IncentiveItemVO;
import com.one.rope.mvp.web.common.dto.admin.team.MemberStudyExperienceItemVO;
import com.one.rope.mvp.web.common.dto.admin.team.MemberWorkExperienceItemVO;
import com.one.rope.mvp.web.common.dto.admin.team.SaveTeamMemberDTO;
import com.one.rope.mvp.basecore.bean.ResponseObject;
import com.one.rope.mvp.web.common.dto.admin.team.TeamMemberDetailVO;
import com.one.rope.mvp.web.common.dto.user.business.BusinessIndexVO;
import com.one.rope.mvp.web.common.dto.user.business.CompanyDetailVO;
import com.one.rope.mvp.web.common.dto.user.business.CompanyMemberListVO;
import com.one.rope.mvp.web.common.dto.user.business.PartnerDetailVO;
import com.one.rope.mvp.web.common.dto.user.business.PartnerListItemVO;
import com.one.rope.mvp.web.common.dto.user.business.PartnerListVO;
import com.one.rope.mvp.web.common.dto.user.business.ProjectDetailVO;
import com.one.rope.mvp.web.common.dto.user.business.ProjectListVO;
import com.one.rope.mvp.web.common.dto.user.business.SavePartnerDTO;
import com.one.rope.mvp.web.common.dto.user.business.SaveProjectDTO;
import com.one.rope.mvp.web.common.enums.MiniProgrameApproveStatusEnum;
import com.one.rope.mvp.web.common.enums.SystemConfigTypeEnum;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 企业端数据服务
 * <p>
 *
 * @author ： Weijian.Liu
 * @date ： 2020/3/15 22:42
 */
@Service
@Slf4j
public class BusinessDataService {

  @Autowired
  IMemberInfoService memberInfoService;

  @Autowired
  ICompanyService companyService;

  @Autowired
  IMemberPushTaskLogService memberPushTaskLogService;

  @Autowired
  ICompanyProjectService companyProjectService;

  @Autowired
  ICompanyMemberService companyMemberService;

  @Autowired
  ICompanyProjectPartnerService companyProjectPartnerService;

  @Autowired
  ICompanyPartnerIncentiveService companyPartnerIncentiveService;

  @Autowired
  ISystemConfigService systemConfigService;

  /**
   * 获取企业端首页数据
   * @return
   */
  public ResponseObject<BusinessIndexVO> businessIndex() {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    BusinessIndexVO resultVO = new BusinessIndexVO();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    if(null == companyId){
      throw new BusinessDataException(BusinessMessage.NOT_VISTI_INDEX);
    }
    Company company = companyService.getById(companyId);
    MyBeanUtils.copyPropertiesIgnoreNull(company, resultVO);
    resultVO.setCompanyName(company.getName());
    List<CompanyProject> projectList = companyProjectService.list(
        new QueryWrapper<CompanyProject>().eq("company_id", companyId)
    );
    List<CompanyProjectPartner> partnerList = companyProjectPartnerService.list(
        new QueryWrapper<CompanyProjectPartner>().eq("company_id", companyId)
    );
    List<CompanyMember> memberList = companyMemberService.list(
        new QueryWrapper<CompanyMember>().eq("company_id", companyId)
    );
    List<MemberPushTaskLog> memberPushTaskLogList = memberPushTaskLogService.selectMemberPushList(userInfo.getMemberInfo().getId());
    resultVO.setProjectNum(projectList.size());
    resultVO.setPartnerNum(partnerList.size());
    resultVO.setMemberNum(memberList.size());
    resultVO.setJobRecommendNum(memberPushTaskLogList.size());
    return new ResponseObject<>(resultVO);
  }

  /**
   * 获取项目列表
   * @return
   */
  public ResponseObject<List<ProjectListVO>> projectList() {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    QueryWrapper<CompanyProject> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("company_id", companyId);
    queryWrapper.orderByDesc("create_time");
    List<CompanyProject> projectList = companyProjectService.list(queryWrapper);
    List<ProjectListVO> resultList = new ArrayList<>();
    if(projectList.size() > 0){
      projectList.stream().forEach(item -> {
        ProjectListVO projectListVO = new ProjectListVO();
        MyBeanUtils.copyPropertiesIgnoreNull(item, projectListVO);
        resultList.add(projectListVO);
      });
    }
    return new ResponseObject<>(resultList);
  }

  /**
   * 保存项目
   * @param requestDTO
   * @return
   */
  public ResponseObject saveProject(SaveProjectDTO requestDTO) {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    Long id = requestDTO.getId();
    CompanyProject companyProject = new CompanyProject();
    MyBeanUtils.copyPropertiesIgnoreNull(requestDTO, companyProject);
    if(null == id || id == 0){
      // 新增
      companyProject.setId(null);
      companyProject.setCompanyId(companyId);
      companyProjectService.save(companyProject);
    }else{
      // 修改
      companyProjectService.updateById(companyProject);
    }
    return ResponseObject.successObject();
  }

  /**
   * 查询项目详情
   * @param projectId
   * @return
   */
  public ResponseObject<ProjectDetailVO> projectDetail(Long projectId) {
    ProjectDetailVO resultVO = new ProjectDetailVO();
    CompanyProject companyProject = companyProjectService.getById(projectId);
    if(null == companyProject){
      throw new BusinessDataException(AdminBusinessMessage.COMPANY_PROJECT_NOT_EXIST);
    }
    MyBeanUtils.copyPropertiesIgnoreNull(companyProject, resultVO);
    if(!StringUtils.isNullOrEmpty(resultVO.getProjectSpot())){
      resultVO.setProjectSpotTagList(CollectionUtils.asList(resultVO.getProjectSpot().split(",")));
    }
    List<CompanyProjectPartner> projectPartnerList = companyProjectPartnerService.list(
        new QueryWrapper<CompanyProjectPartner>().eq("project_id", projectId)
    );
    if(projectPartnerList.size() > 0){
      resultVO.setIsBindPartner(1);
    }

    return new ResponseObject<>(resultVO);
  }

  /**
   * 删除项目
   * @param projectId
   * @return
   */
  public ResponseObject delProject(Long projectId) {
    return companyProjectService.deleteProject(projectId);
  }

  /**
   * 查询合伙人岗位列表
   * @return
   */
  public ResponseObject<List<PartnerListVO>> partnerList() {
    List<PartnerListVO> resultList = new ArrayList<>();
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    List<PartnerListItemVO> partnerListItemList = companyProjectPartnerService.selectPartnerList(userInfo.getMemberInfo().getCompanyId());
    if(partnerListItemList.size() > 0){
      Map<String, List<PartnerListItemVO>> nameGroupMap = partnerListItemList.stream().collect(Collectors.groupingBy(PartnerListItemVO::getProjectName));
      for (String key: nameGroupMap.keySet()){
        PartnerListVO partnerListVO = new PartnerListVO();
        partnerListVO.setProjectName(key);
        partnerListVO.setPartnerList(nameGroupMap.get(key));
        resultList.add(partnerListVO);
      }
    }

    return new ResponseObject<>(resultList);
  }

  /**
   * 查询合伙人岗位详情
   * @param partnerId
   * @return
   */
  public ResponseObject<PartnerDetailVO> partnerDetail(Long partnerId) {
    PartnerDetailVO resultVO = new PartnerDetailVO();
    CompanyPartnerDetailVO detailVO = companyProjectPartnerService.partnerDetail(partnerId);
    MyBeanUtils.copyPropertiesIgnoreNull(detailVO, resultVO);
    SystemConfig systemConfig = systemConfigService.getOne(
        new QueryWrapper<SystemConfig>().eq("type", SystemConfigTypeEnum.COFIG1.getCode()));

    // 查询企业信息
    Company company = companyService.getById(detailVO.getCompanyId());
    resultVO.setCompanyValue(company.getCompanyValue());
    resultVO.setValueCurrency(company.getValueCurrency());
    resultVO.setCompanynName(company.getName());
    resultVO.setFinanceStage(company.getFinanceStage());
    resultVO.setMemberScale(company.getMemberScale());
    resultVO.setValuationOrg(company.getValuationOrg());

    // 小程序审核完成才正常返回数据
    if(Integer.parseInt(systemConfig.getValue()) == MiniProgrameApproveStatusEnum.COMPLETE.getCode()){
      CompanyProjectPartner projectPartner = companyProjectPartnerService.getById(partnerId);
      if(null == projectPartner){
        throw new BusinessDataException(AdminBusinessMessage.COMPANY_PARTNER_NOT_EXIST);
      }
      //设置所属项目
      CompanyProject companyProject = companyProjectService.getById(projectPartner.getProjectId());
      if(null == companyProject){
        throw new BusinessDataException(AdminBusinessMessage.COMPANY_PROJECT_NOT_EXIST);
      }
      ProjectDetailVO projectDetailVO = new ProjectDetailVO();
      MyBeanUtils.copyPropertiesIgnoreNull(companyProject, projectDetailVO);
      if(!StringUtils.isNullOrEmpty(companyProject.getProjectSpot())){
        projectDetailVO.setProjectSpotTagList(CollectionUtils.asList(companyProject.getProjectSpot().split(",")));
      }
      resultVO.setProject(projectDetailVO);

      //设置核心团队成员列表
      List<TeamMemberDetailVO> teamMemberList = new ArrayList<>();
      List<CompanyMember> companyMemberList = companyMemberService.list(
          new QueryWrapper<CompanyMember>().eq("company_id", projectPartner.getCompanyId())
      );
      companyMemberList.stream().forEach(item -> {
        TeamMemberDetailVO memberDetailVO = new TeamMemberDetailVO();
        MyBeanUtils.copyPropertiesIgnoreNull(item, memberDetailVO);

        List<String> skilledList = new ArrayList<>();
        List<MemberWorkExperienceItemVO> workExperienceList = new ArrayList<>();
        List<MemberStudyExperienceItemVO> studyExperienceList = new ArrayList<>();
        // 设置擅长技能
        String skilled = item.getSkilled();
        if (!StringUtils.isNullOrEmpty(skilled)) {
          skilledList = CollectionUtils.asList(skilled.split(","));
        }

        // 设置工作经验
        String workExperience = item.getWorkExperience();
        if (!StringUtils.isNullOrEmpty(workExperience)) {
          workExperienceList = JsonUtils.stringToList(workExperience, MemberWorkExperienceItemVO.class);
        }

        // 设置教育经验
        String studyExperience = item.getStudyExperience();
        if (!StringUtils.isNullOrEmpty(studyExperience)) {
          studyExperienceList = JsonUtils.stringToList(studyExperience, MemberStudyExperienceItemVO.class);
        }

        memberDetailVO.setSkilledList(skilledList);
        memberDetailVO.setWorkExperienceList(workExperienceList);
        memberDetailVO.setStudyExperienceList(studyExperienceList);

        teamMemberList.add(memberDetailVO);
      });
      resultVO.setTeamMemberList(teamMemberList);

    }else{
      resultVO.setRequireDesc(null);
      resultVO.setIncentiveList(null);
    }

    return new ResponseObject<>(resultVO);
  }

  /**
   * 删除合伙人岗位
   * @param partnerId
   * @return
   */
  public ResponseObject delPartner(Long partnerId) {
    companyProjectPartnerService.deletePartner(partnerId);
    return ResponseObject.successObject();
  }

  /**
   * 保存合伙人岗位
   * @param requestDTO
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  public ResponseObject savePartner(SavePartnerDTO requestDTO) {
    CompanyProjectPartner companyProjectPartner = new CompanyProjectPartner();
    MyBeanUtils.copyPropertiesIgnoreNull(requestDTO, companyProjectPartner);
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    companyProjectPartner.setCompanyId(userInfo.getMemberInfo().getCompanyId());
    if(requestDTO.getId() == 0){
      companyProjectPartner.setId(null);
    }
    companyProjectPartnerService.saveOrUpdate(companyProjectPartner);

    // 更新合伙人的激励方案
    List<IncentiveItemVO> incentiveItemVOList = requestDTO.getIncentiveList();
    if (null != incentiveItemVOList && incentiveItemVOList.size() > 0) {
      incentiveItemVOList.stream().forEach(item -> {
        CompanyPartnerIncentive companyPartnerIncentive = new CompanyPartnerIncentive();
        MyBeanUtils.copyPropertiesIgnoreNull(item, companyPartnerIncentive);
        if(null != item.getId() && item.getId() == 0){
          companyPartnerIncentive.setId(null);
        }
        companyPartnerIncentive.setPartnerId(companyProjectPartner.getId());
        companyPartnerIncentiveService.saveOrUpdate(companyPartnerIncentive);
      });
    }

    return ResponseObject.successObject();
  }

  /**
   * 编辑企业
   * @return
   */
  public ResponseObject editCompany(EditCompanyDTO editCompanyDTO) {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    editCompanyDTO.setId(companyId);
    companyService.editCompany(editCompanyDTO);
    return ResponseObject.successObject();
  }

  /**
   * 查询核心团队成员列表
   * @return
   */
  public ResponseObject<List<CompanyMemberListVO>> companyMemberList() {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    List<CompanyMemberListVO> resultVO = new ArrayList<>();
    List<CompanyMember> companyMemberList = companyMemberService.list(
        new QueryWrapper<CompanyMember>().eq("company_id", companyId)
    );
    companyMemberList.stream().forEach(item -> {
      CompanyMemberListVO listVO = new CompanyMemberListVO();
      MyBeanUtils.copyPropertiesIgnoreNull(item, listVO);
      resultVO.add(listVO);
    });
    return new ResponseObject<>(resultVO);
  }

  /**
   * 保存核心团队成员
   * @param requestDTO
   * @return
   */
  public ResponseObject saveCompanyMember(SaveTeamMemberDTO requestDTO) {
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    if(null == requestDTO.getId() || requestDTO.getId() == 0){
      requestDTO.setCompanyId(companyId);
    }
    return companyMemberService.saveTeamMember(requestDTO);
  }

  /**
   * 删除核心团队成员
   * @param id
   * @return
   */
  public ResponseObject delCompanyMember(Long id) {
    return companyMemberService.deleteTeamMember(id);
  }

  /**
   * 查询核心团队成员详情
   * @param id
   * @return
   */
  public ResponseObject companyMemberDetail(Long id) {
    return companyMemberService.teamMemberDetail(id);
  }

  /**
   * 查询企业详情
   * @return
   */
  public ResponseObject<CompanyDetailVO> companyDetail() {
    CompanyDetailVO resultVO = new CompanyDetailVO();
    UserInfo userInfo = UserLoginUtil.getUserInfo();
    Long companyId = userInfo.getMemberInfo().getCompanyId();
    Company company = companyService.getById(companyId);
    MyBeanUtils.copyPropertiesIgnoreNull(company, resultVO);
    return new ResponseObject<>(resultVO);
  }
}
